package com.haitaoit.chengquan.module.home;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.model.LatLng;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.ExitApplication;
import com.haitaoit.chengquan.bean.HomeMoreServceBeen;
import com.haitaoit.chengquan.main.MianButtonActivity;
import com.haitaoit.chengquan.module.home.activity.CreditSearchActivity;
import com.haitaoit.chengquan.module.home.activity.HelpActivity;
import com.haitaoit.chengquan.module.home.activity.LocationCityActivity;
import com.haitaoit.chengquan.module.home.activity.SearchActivity;
import com.haitaoit.chengquan.module.home.activity.forum.ForumCenterActivity;
import com.haitaoit.chengquan.module.home.activity.maintenance.MaintenanceActivity;
import com.haitaoit.chengquan.module.home.activity.maintenance.QFacilityMaintenanceActivity;
import com.haitaoit.chengquan.module.home.activity.parts.PartsActivity;
import com.haitaoit.chengquan.module.home.activity.pinpai.BrandActivity;
import com.haitaoit.chengquan.module.home.activity.zhaopin.RecruitActivity;
import com.haitaoit.chengquan.module.home.adapter.HomePartsAdapter;
import com.haitaoit.chengquan.module.home.model.TitleModel;
import com.haitaoit.chengquan.ui.equipment.activity.ShowPictureActivity;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.ImageCycleView;
import com.haitaoit.chengquan.view.Img;
import com.haitaoit.chengquan.view.MyGridView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.squareup.leakcanary.RefWatcher;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by Administrator on 2016/9/22.
 */
public class HomeFragment extends Fragment {
    @ViewInject(R.id.home_address)
    TextView   home_address;
    @ViewInject(R.id.fastfragent_textone)
    TextView   fastfragent_textone;
    @ViewInject(R.id.fastfragent_texttwo)
    TextView   fastfragent_texttwo;
    @ViewInject(R.id.fastfragent_textthree)
    TextView   fastfragent_textthree;
    @ViewInject(R.id.fastfragent_textfour)
    TextView   fastfragent_textfour;
    @ViewInject(R.id.fastfragent_textfive)
    TextView   fastfragent_textfive;
    @ViewInject(R.id.fastfragent_textsix)
    TextView   fastfragent_textsix;
    @ViewInject(R.id.home_worke_line)
    TextView   home_worke_line;
    @ViewInject(R.id.home_topImg)
    Banner     home_topImg;
    //    ImageCycleView home_topImg;
    @ViewInject(R.id.home_list_pj)
    MyGridView home_list_pj;
    BDLocationListener mListener;

    private HomePartsAdapter Partsadapter;// 配件商城
    private List<TitleModel> mList;
    private List<String> mImgUrl = new ArrayList<String>();
    private Gson   mGson;
    private String mSubstring;
    private String mAccount_type;
    private String mUserID;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_home, null);
        ViewUtils.inject(this, v);
        mAccount_type = PreferenceUtils.getPrefString("account_type", "");
        mUserID = PreferenceUtils.getPrefString("user_id", "");
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        ViewGroup.LayoutParams lp1 = home_topImg.getLayoutParams();
        lp1.height = metrics.widthPixels / 3;
        home_topImg.setLayoutParams(lp1);
        mGson = new Gson();
        PreferenceUtils.setPrefString("choice_city", "");

        Partsadapter = new HomePartsAdapter(getActivity());
        Partsadapter.setBackCall(backCall);
        home_list_pj.setAdapter(Partsadapter);
        home_topImg.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {

                if ((mImgUrl.size() - 1) >= position) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), ShowPictureActivity.class);
                    intent.putExtra("image_uri", mImgUrl.get(position));
                    startActivity(intent);
                }
            }
        });

        //获取当前的位置
        mListener = new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {

                if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                    LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
                    MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                    MapStatusUpdate u1 = MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().zoom(11).build());

                }
                if (!("").equals(location.getCity())) {
                    if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                        //保存起来，以供home页面来定位
                        PreferenceUtils.setPrefString("location_city", location.getCity());
                        //保存起来，以供home页面来定位
                    } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                        PreferenceUtils.setPrefString("location_city", location.getCity());
                        //保存起来，以供home页面来定位
                    } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                        PreferenceUtils.setPrefString("location_city", location.getCity());
                    } else {
                        PreferenceUtils.setPrefString("location_city", "");
                    }
                }
            }

        };
        //获取更多服务内容下面的修改列表
        haveMoreData();

        return v;
    }

    private void haveMoreData() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("rnd", "0");
        final String sign = GetSign.getSign(map);

        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpUtils
                        .get()
                        .url(Constant.GETMODULAR_LIST)
                        .addParams("rnd", "0")
                        .addParams("sign", sign)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                ToastUtils.showToast("获取数据失败");

                            }

                            @Override
                            public void onResponse(String response, int id) {
                                final HomeMoreServceBeen been = mGson.fromJson(response, HomeMoreServceBeen.class);
                                if (been == null) {
                                    ToastUtils.showToast("获取数据失败");
                                    return;
                                }
                                if (!TextUtils.equals("0", been.getErrCode())) {
                                    ToastUtils.showToast(been.getErrMsg());
                                    return;
                                }
                                if (TextUtils.equals("0", been.getErrCode())) {
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            List<HomeMoreServceBeen.ResponseBean> list = been.getResponse();
                                            for (int i = 0; i < list.size(); i++) {
                                                if (i == 0) {
                                                    fastfragent_textone.setText(been.getResponse().get(i).getModulardesc());
                                                }
                                                if (i == 1) {
                                                    fastfragent_texttwo.setText(been.getResponse().get(i).getModulardesc());
                                                }
                                                if (i == 2) {
                                                    fastfragent_textthree.setText(been.getResponse().get(i).getModulardesc());
                                                }
                                                if (i == 3) {
                                                    fastfragent_textfour.setText(been.getResponse().get(i).getModulardesc());
                                                }
                                                if (i == 4) {
                                                    fastfragent_textfive.setText(been.getResponse().get(i).getModulardesc());
                                                }
                                                if (i == 5) {
                                                    fastfragent_textsix.setText(been.getResponse().get(i).getModulardesc());
                                                }
                                            }
                                        }
                                    });

                                }

                            }
                        });
            }
        }).start();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        home_topImg.setImageLoader(new GlideImageLoader());
        home_topImg.setDelayTime(3000);
        //        httpGetHomeBanner();
    }

    BackCall backCall = new BackCall() {
        @Override
        public void deal(int which, Object... obj) {
            int position = (Integer) obj[0];
            Intent intent = new Intent();
            switch (which) {
                case R.id.home_dqpj_item:
                    intent.setClass(getActivity(), PartsActivity.class);
                    intent.putExtra("selectId", Partsadapter.getList().get(position).getId());
                    startActivity(intent);
                    break;
            }
            super.deal(which, obj);
        }
    };

    @Override
    public void onResume() {

        String location_city = PreferenceUtils.getPrefString("location_city", "");
        if (TextUtils.isEmpty(location_city)) {
            home_address.setText("未知");
        }
        if (location_city.contains("市") || location_city.contains("省")) {
            mSubstring = location_city.substring(0, location_city.length() - 1);
        }
        home_address.setText(mSubstring);
        if (!TextUtils.isEmpty(PreferenceUtils.getPrefString("choice_city", ""))) {
            home_address.setText(PreferenceUtils.getPrefString("choice_city", ""));
        }

        httpGetHomeBanner();

        if (Partsadapter == null) {
            Partsadapter = new HomePartsAdapter(getActivity());
            Partsadapter.setBackCall(backCall);
            home_list_pj.setAdapter(Partsadapter);
            String Response = PreferenceUtils.getPrefString("HOMELIST", "");
            mList = mGson.fromJson(Response,
                    new TypeToken<List<TitleModel>>() {
                    }.getType());

            Partsadapter.setList(mList);
        } else {
            String Response = PreferenceUtils.getPrefString("HOMELIST", "");
            mList = mGson.fromJson(Response,
                    new TypeToken<List<TitleModel>>() {
                    }.getType());
            Partsadapter.setBackCall(backCall);
            Partsadapter.setList(mList);
            Partsadapter.notifyDataSetChanged();
        }


        super.onResume();
    }

    @OnClick({R.id.home_address, R.id.home_search_LL, R.id.home_sbwx,
            R.id.home_jgdd, R.id.home_jchc, R.id.home_jcpj, R.id.home_jczl,
            R.id.home_old_sbmm, R.id.home_old_sbgz, R.id.home_xtwx, R.id.home_pptj,
            R.id.home_zpyp, R.id.home_ltzx, R.id.home_xycx, R.id.home_bzzx,R.id.home_worke_line
           /*R.id.home_dqpj, R.id.home_xtpj, R.id.home_jxpj,*/})
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.home_address:// 定位地址
                PreferenceUtils.setPrefString("choice_city", "");
                intent.setClass(getActivity(), LocationCityActivity.class);
                startActivity(intent);
                break;
            case R.id.home_search_LL:// 搜索
                intent.setClass(getActivity(), SearchActivity.class);
                intent.putExtra("type", "home");
                startActivity(intent);
                break;
            case R.id.home_sbwx:// 设备维修
                intent.setClass(getActivity(), QFacilityMaintenanceActivity.class);
                intent.putExtra("type_id", 1);
                intent.putExtra("my_type", 1);
                startActivity(intent);
                break;
            case R.id.home_jgdd:// 加工订单
                intent.setClass(getActivity(), QFacilityMaintenanceActivity.class);
                intent.putExtra("type_id", 2);
                intent.putExtra("my_type", 2);
                startActivity(intent);
                break;
            case R.id.home_jchc:// 机床耗材
                intent.setClass(getActivity(), QFacilityMaintenanceActivity.class);
                intent.putExtra("type_id", 3);
                intent.putExtra("my_type", 3);
                startActivity(intent);
                break;
            case R.id.home_jcpj:// 机床配件
                intent.setClass(getActivity(), QFacilityMaintenanceActivity.class);
                intent.putExtra("type_id", 4);
                intent.putExtra("my_type", 4);
                startActivity(intent);
                break;
            case R.id.home_jczl:// 机床组立
                intent.setClass(getActivity(), QFacilityMaintenanceActivity.class);
                intent.putExtra("type_id", 5);
                intent.putExtra("my_type", 5);
                startActivity(intent);
                break;
            case R.id.home_old_sbmm:// 二手设备买卖
                intent.setClass(getActivity(), QFacilityMaintenanceActivity.class);
                intent.putExtra("type_id", 6);
                intent.putExtra("my_type", 6);
                startActivity(intent);
                break;
            case R.id.home_old_sbgz:// 二手设备改造
                intent.setClass(getActivity(), QFacilityMaintenanceActivity.class);
                intent.putExtra("type_id", 7);
                intent.putExtra("my_type", 7);
                startActivity(intent);
                break;
            /**case R.id.home_dqpj:// 电气配件
             case R.id.home_xtpj:// 系统配件
             case R.id.home_jxpj:// 机械配件
             intent.setClass(getActivity(), PartsActivity.class);
             intent.putExtra("selectId", "0");
             startActivity(intent);
             break;*/
            case R.id.home_xtwx:// 系统维修
                intent.setClass(getActivity(), MaintenanceActivity.class);
                startActivity(intent);
                break;
            case R.id.home_pptj:// 品牌推荐
                intent.setClass(getActivity(), BrandActivity.class);
                startActivity(intent);
                break;
            case R.id.home_zpyp:// 招聘应聘
                intent.setClass(getActivity(), RecruitActivity.class);
                startActivity(intent);
                break;
            case R.id.home_ltzx:// 论坛中心
                intent.setClass(getActivity(), ForumCenterActivity.class);
                startActivity(intent);
                break;
            case R.id.home_xycx:// 信誉查询
                intent.setClass(getActivity(), CreditSearchActivity.class);
                startActivity(intent);
                break;
            case R.id.home_bzzx:// 帮助中心
                intent.setClass(getActivity(), HelpActivity.class);
                startActivity(intent);
                break;
            case R.id.home_worke_line:// 行业圈
                intent.setClass(getActivity(), ForumCenterActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void httpGetHomeBanner() {
        List<NameValuePairSign> pair = new ArrayList<>();
        pair.add(new NameValuePairSign("code", "201610251802344784"));
        String sign = GetSign.genPackageSign(pair);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("code", "201610251802344784");
        params.addQueryStringParameter("sign", sign);
        HttpUtilsSingle.doGet(getActivity(), false, Constant.Getads_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result.toString();
                List<Img> imglist = new ArrayList<Img>();

                try {
                    JSONObject json = new JSONObject(result);
                    String ErrCode = json.getString("ErrCode");
                    String ErrMsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    if (Integer.valueOf(ErrCode) == 0) {
                        imglist = gson.fromJson(Response, new TypeToken<ArrayList<Img>>() {
                        }.getType());

                        if (mImgUrl.size() != 0) {
                            mImgUrl.clear();
                        }
                        for (int i = 0; i < imglist.size(); i++) {
                            mImgUrl.add(imglist.get(i).getImg_url());
                            //                            PreferenceUtils.setImgUrl();
                        }
                        //设置图片集合
                        home_topImg.setImages(mImgUrl);
                        //banner设置方法全部调用完毕时最后调用
                        home_topImg.start();
                        setImgList(mImgUrl);
                        //                        home_topImg.setImageResources(imglist, listener);
                    } else {
                        ToastUtils.showToast(ErrMsg);
                        ToastUtils.showToast(ErrMsg);
                    }
                    httpGetgoods_class_list();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                httpGetgoods_class_list();
                //设置图片集合
                if (getImgList() != null && getImgList().size() > 0) {
                    home_topImg.setImages(getImgList());
                }
                //banner设置方法全部调用完毕时最后调用
                home_topImg.start();
                ToastUtils.showToast("获取数据失败，请检查网路！");
            }
        });
    }

    public void setImgList(List<String> datalist) {
        if (null == datalist || datalist.size() <= 0)
            return;
        Gson gson = new Gson();
        //转换成json数据，再保存
        String strJson = gson.toJson(datalist);
        PreferenceUtils.setImgUrl(strJson);
    }

    public List<String> getImgList() {
        List<String> datalist = new ArrayList<String>();
        String imgUrl = PreferenceUtils.getImgUrl();
        Gson gson = new Gson();
        datalist = gson.fromJson(imgUrl, new TypeToken<List<String>>() {
        }.getType());
        return datalist;
    }

    @Override
    public void onStart() {
        super.onStart();
        home_topImg.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        home_topImg.stopAutoPlay();
    }

    // 品牌
    private void httpGetgoods_class_list() {
        int i = (int) Math.floor(Math.random() * 9000 + 1000);
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("rnd", i + ""));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("rnd", i + "");
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(getActivity(), false, Constant.Getgoods_class_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");

                    if (mGson == null) {
                        mGson = new Gson();
                    }
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            PreferenceUtils.setPrefString("HOMELIST", Response);
                            mList = mGson.fromJson(Response,
                                    new TypeToken<List<TitleModel>>() {
                                    }.getType());

                            Partsadapter.setList(mList);


                            Partsadapter.notifyDataSetChanged();
                            if (!PreferenceUtils.getPrefString("user_id", "").equals("")) {
                                httpGetpd_userlogin();
                            }
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                if (!PreferenceUtils.getPrefString("user_id", "").equals("")) {
                    httpGetpd_userlogin();
                }
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    private void httpGetpd_userlogin() {// 获取手机唯一标识
        TelephonyManager TelephonyMgr = (TelephonyManager) ExitApplication.context.getSystemService(Activity.TELEPHONY_SERVICE);
        String equipment = TelephonyMgr.getDeviceId();
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("equipment", equipment));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("equipment", equipment);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(getActivity(), false, Constant.Getpd_userlogin, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            if (Errmsg.equals("未找到用户")) {
                                PreferenceUtils.setPrefString("user_id", "");
                                PreferenceUtils.setPrefString("account_type", "");
                            }
                            return;
                        case 0:// 成功
                            JSONObject js = new JSONObject(Response);
                            if ("1".equals(js.getString("status"))) {
                                PreferenceUtils.setPrefString("user_id", "");
                                PreferenceUtils.setPrefString("account_type", "");
                            }
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    /**
     * 轮播图点击事件
     */
    ImageCycleView.ImageCycleViewListener listener = new ImageCycleView.ImageCycleViewListener() {
        @Override
        public void displayImage(Img img, ImageView imageView) {
            //            ImageLoader.getInstance().displayImage(img.getImg_url(), imageView);
            Log.i("======", "=========" + imageView.getTag());
            //            Glide.with(getActivity()).load(img.getImg_url()).into(imageView);
        }

        @Override
        public void onImageClick(int position, View imageView) {
        }

        @Override
        public void onImageChange(int position, List<Img> imageUrlList) {
        }
    };

    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            Log.i("=====", "==" + path);
            Glide.with(context).load(path).into(imageView);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RefWatcher refWatcher = ExitApplication.getRefWatcher(getActivity());
        refWatcher.watch(this);
    }
}
